<?php
Raise::load('core.RaiseObject');
Raise::load('core.io.RaiseConsoleStream');
Raise::load('core.collection.RaiseCollection');

/**
 * RaiseConsoleApplication class
 * represents a PHP application that is accessed via the console
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.core
 * @since 1.2
 */
class RaiseConsoleApplication extends RaiseObject {

    /**
     * A collection of arguments passed into the script
     * @var RaiseCollection
     */
    private $arguments;

    /**
     * The stream for console input/output
     * @var RaiseStream
     */
    private $stream;

    /**
     * Create a new RaiseConsoleApplication
     * @param array $params (optional) The variable $argv passed into the script
     */
    public function __construct($params = array()){
        if(php_sapi_name() != 'cli'){
            throw new RaiseInvalidRequestException('RaiseConsoleApplication cannot run from a non-Command Line Interface (CLI).');
        }
        $this->arguments = self::parseArgs($params);
        $this->stream = new RaiseConsoleStream();
    }

    /**
     * Get the arguments passed to this console application
     * @return RaiseCollection
     */
    public function arguments(){
        return $this->arguments;
    }

    /**
     * Get the stream for console input/output
     * @return RaiseStream
     */
    public function stream(){
        return $this->stream;
    }

    private static function parseArgs($params){
        array_shift($params);
        $out = array();
        foreach ($params as $arg){
            if (substr($arg, 0, 2) == '--'){
                $eqPos = strpos($arg, '=');
                if ($eqPos === false){
                    $key = substr($arg, 2);
                    $out[$key] = isset($out[$key]) ? $out[$key] : true;
                } else {
                    $key = substr($arg, 2, $eqPos - 2);
                    $out[$key] = substr($arg, $eqPos + 1);
                }
            } else if (substr($arg, 0, 1) == '-'){
                if (substr($arg, 2, 1) == '='){
                    $key = substr($arg, 1, 1);
                    $out[$key] = substr($arg, 3);
                } else {
                    $chars = str_split(substr($arg, 1));
                    foreach ($chars as $c){
                        $key = $c;
                        $out[$key] = isset($out[$key]) ? $out[$key] : true;
                    }
                }
            } else {
                $out[] = $arg;
            }
        }
        return new RaiseCollection($out);
    }

}